package jmind.core.pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * description:  html格式生成pdf
 * https://blog.csdn.net/hj7jay/article/details/102605521
 * https://blog.csdn.net/u012174571/article/details/46126281?spm=ata.21736010.0.0.2e921e92A4MBvW
 * https://blog.csdn.net/weixin_30292745/article/details/99905028
 * https://www.cnblogs.com/whalesea/p/11752086.html
 * https://blog.csdn.net/weixin_30333885/article/details/97709188?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-2.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-2.nonecase
 *
 * @author weibo.xie
 * @date : create in 2:31 下午 2021/7/20
 */
public class Html2Pdf {

    private String baseFontPath="/Users/weibo/workspace/jmind/jmind-core/src/main/resources/simsun.ttc";

    public Html2Pdf(String baseFontPath){
        this.baseFontPath=baseFontPath;
    }

    /**
     * 根据html生成pdf
     * @param content html内容
     * @param dest
     * @throws IOException
     * @throws DocumentException
     */
    public  void createPdf(String content,String dest) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        // step 3
        document.open();
        // step 4
        // XMLWorkerHelper.getInstance().parseXHtml(writer, document, reader);
        XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
        fontImp.register(baseFontPath);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"), fontImp);
        // step 5
        document.close();
    }

    /**
     * 利用css3 样式生成pdf
     * @param content  html内容
     * @param dest
     * @throws Exception
     */
    public  void createCss3Pdf(String content,String dest) throws Exception {
        ITextRenderer render = new ITextRenderer();
        //设置字体
        ITextFontResolver fontResolver = render.getFontResolver();
        fontResolver.addFont(baseFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        // 解析html生成pdf
        render.setDocumentFromString(content);
        render.layout();
        render.createPDF(new FileOutputStream(dest));
        render.finishPDF();
    }


}